﻿using RpcHelper;
using RpcSync.Model;
using RpcSync.Model.DB;
using SqlSugar;
using SqlSugarHelper;

namespace RpcSync.DAL.Repository
{
    internal class RemoteServerConfigDAL : IRemoteServerConfigDAL
    {
        private IRepository<RemoteServerConfigModel> _BasicDAL;
        public RemoteServerConfigDAL(IRepository<RemoteServerConfigModel> dal)
        {
            _BasicDAL = dal;
        }
        public ServerState GetServerState()
        {
            return this._BasicDAL.Queryable.Select(c => new ServerState
            {
                Count = SqlFunc.RowCount(),
                MaxTime = SqlFunc.AggregateMax(c.AddTime)
            }).First();
        }

        public RemoteServer[] GetServer()
        {
            DateTime time = HeartbeatTimeHelper.CurrentDate.AddDays(-1);
            return this._BasicDAL.Gets(c => (c.ServiceState == RpcModel.RpcServiceState.正常 && c.IsOnline) || (c.IsOnline == false && c.LastOffliceDate >= time), c => new RemoteServer
            {
                GroupId = c.GroupId,
                Id = c.Id,
                RegionId = c.RegionId,
                SystemType = c.SystemType
            });
        }
        public RemoteServerConfig GetServer(long serverId)
        {
            return this._BasicDAL.Get(c => c.Id == serverId, c => new RemoteServerConfig
            {
                ConIp = c.ConIp,
                RemoteIp = c.RemoteIp,
                ServerIp = c.ServerIp,
                ServerName = c.ServerName,
                ServerPort = c.ServerPort
            });
        }
    }
}
